const fs = require('fs');
const path = require('path');

// 需要更新的页面目录
const pageDirs = [
  'pages/service',
  'pages/user',
  'pages/village',
  'pages/admin',
  'pages/auth',
  'pages/common',
  'pages/activity'
];

// 需要更新的文件模式
const filePatterns = [
  'index.js',
  'profile/index.js',
  'apply/index.js',
  'detail/index.js'
];

// 更新函数
function updatePageWithSmartLoading(filePath) {
  try {
    let content = fs.readFileSync(filePath, 'utf8');
    let modified = false;

    // 获取页面名称
    const relativePath = path.relative(path.join(__dirname, '..'), filePath);
    const pageName = relativePath.replace(/\\/g, '/').replace('.js', '');

    // 1. 添加智能加载管理器引用
    if (!content.includes('smartLoadingManager') && content.includes('pageLoadingManager')) {
      content = content.replace(
        /const pageLoadingManager = require\([^)]+\)/g,
        'const pageLoadingManager = require(\'../../../utils/pageLoadingManager\')\nconst smartLoadingManager = require(\'../../../utils/smartLoadingManager\')'
      );
      modified = true;
    }

    // 2. 更新onLoad方法中的页面加载调用
    const onLoadPattern = /onLoad\([^)]*\)\s*\{[\s\S]*?pageLoadingManager\.onPageEnter\([^)]+\)[\s\S]*?\}/g;
    if (onLoadPattern.test(content)) {
      content = content.replace(onLoadPattern, (match) => {
        // 提取pageLoadingManager.onPageEnter调用
        const pageEnterMatch = match.match(/pageLoadingManager\.onPageEnter\([^)]+\)/);
        if (pageEnterMatch) {
          modified = true;
          return match.replace(pageEnterMatch[0], `smartLoadingManager.onPageEnter('${pageName}')`);
        }
        return match;
      });
    }

    // 3. 更新onReady方法
    const onReadyPattern = /onReady\(\)\s*\{[\s\S]*?pageLoadingManager\.onPageDataLoaded\([^)]+\)[\s\S]*?\}/g;
    if (onReadyPattern.test(content)) {
      content = content.replace(onReadyPattern, (match) => {
        // 提取pageLoadingManager.onPageDataLoaded调用
        const pageDataLoadedMatch = match.match(/pageLoadingManager\.onPageDataLoaded\([^)]+\)/);
        if (pageDataLoadedMatch) {
          modified = true;
          return match.replace(pageDataLoadedMatch[0], `smartLoadingManager.onPageDataLoaded('${pageName}')`);
        }
        return match;
      });
    }

    // 4. 更新数据加载完成后的调用
    const dataLoadedPattern = /this\.hideGlobalLoading\(\);?\s*console\.log\([^)]*加载成功[^)]*\)/g;
    if (dataLoadedPattern.test(content)) {
      content = content.replace(dataLoadedPattern, (match) => {
        modified = true;
        return `smartLoadingManager.onPageDataLoaded('${pageName}');\n        console.log('数据加载成功');`;
      });
    }

    // 5. 更新错误处理中的调用
    const errorPattern = /this\.hideGlobalLoading\(\);?\s*wx\.showToast\([\s\S]*?icon:\s*'none'[\s\S]*?\}\)/g;
    if (errorPattern.test(content)) {
      content = content.replace(errorPattern, (match) => {
        modified = true;
        return match.replace('this.hideGlobalLoading();', `smartLoadingManager.forceHidePageLoading('${pageName}');`);
      });
    }

    if (modified) {
      fs.writeFileSync(filePath, content, 'utf8');
      console.log(`✅ 已更新: ${filePath}`);
      return true;
    } else {
      console.log(`⏭️  无需更新: ${filePath}`);
      return false;
    }
  } catch (error) {
    console.error(`❌ 更新失败: ${filePath}`, error.message);
    return false;
  }
}

// 递归查找文件
function findFiles(dir, patterns) {
  const files = [];
  
  function traverse(currentDir) {
    try {
      const items = fs.readdirSync(currentDir);
      
      for (const item of items) {
        const fullPath = path.join(currentDir, item);
        const stat = fs.statSync(fullPath);
        
        if (stat.isDirectory()) {
          traverse(fullPath);
        } else if (stat.isFile() && patterns.some(pattern => item === pattern)) {
          files.push(fullPath);
        }
      }
    } catch (error) {
      console.warn(`⚠️  无法访问目录: ${currentDir}`, error.message);
    }
  }
  
  traverse(dir);
  return files;
}

// 主函数
function main() {
  console.log('🔧 开始更新页面使用智能加载管理器...\n');
  
  let totalUpdated = 0;
  let totalSkipped = 0;
  
  for (const pageDir of pageDirs) {
    const fullPath = path.join(__dirname, '..', pageDir);
    
    if (!fs.existsSync(fullPath)) {
      console.log(`⚠️  目录不存在: ${fullPath}`);
      continue;
    }
    
    console.log(`📁 处理目录: ${pageDir}`);
    
    const files = findFiles(fullPath, filePatterns);
    
    for (const file of files) {
      if (updatePageWithSmartLoading(file)) {
        totalUpdated++;
      } else {
        totalSkipped++;
      }
    }
    
    console.log('');
  }
  
  console.log('🎉 更新完成!');
  console.log(`✅ 已更新: ${totalUpdated} 个文件`);
  console.log(`⏭️  跳过: ${totalSkipped} 个文件`);
}

// 运行脚本
if (require.main === module) {
  main();
}

module.exports = { updatePageWithSmartLoading, findFiles };
